package message

import (
	"fmt"
	"hash/fnv"
	"strconv"
	"time"

	"gitee.com/lyuanbo/stock-plus/internal/svc"
	"gitee.com/lyuanbo/stock-plus/pkg/consts"
	"gitee.com/lyuanbo/stock-plus/pkg/message"
	"gitee.com/lyuanbo/stock-plus/pkg/notifier/bark"
	storagememory "gitee.com/lyuanbo/stock-plus/pkg/stock/storage_memory"
	"gitee.com/lyuanbo/stock-plus/pkg/worker_manager"
	"github.com/bytedance/sonic"
	"github.com/nats-io/nats.go"
	"go.uber.org/zap"
)

func init() {
	workermanager.Register(func(svcCtx *svc.ServiceContext, _ *storagememory.Cache) workermanager.Tasker {
		return New(svcCtx)
	})
}

type Message struct {
	svcCtx *svc.ServiceContext
}

func New(svcCtx *svc.ServiceContext) *Message {
	return &Message{svcCtx: svcCtx}
}

func (m *Message) Init() {}

func (m *Message) Name() string {
	return "message"
}

func (m *Message) Start() {
	go m.Run()
}

func (m *Message) Run() {
	_, _ = m.svcCtx.Nats.Subscribe(consts.TopicMessage, func(msg *nats.Msg) {
		var tMsg message.Message
		if err := sonic.Unmarshal(msg.Data, &tMsg); err != nil {
			m.svcCtx.Logger.Warn(m.svcCtx.Ctx, "unmarshal bark message error", zap.Error(err))
			return
		}

		if tMsg.Key == "" {
			tMsg.Key = tMsg.Title
		}
		// 查询是否已推送
		h := fnv.New64a()
		_, _ = h.Write([]byte(tMsg.Key))
		key := fmt.Sprintf("message:push:%s", strconv.FormatUint(h.Sum64(), 36))
		if m.svcCtx.Redis.Exists(m.svcCtx.Ctx, key).Val() == 1 {
			return
		}

		bark.Send(&tMsg)

		if tMsg.Expire == 0 {
			tMsg.Expire = 5 * 60 // 默认 5 分钟
		}

		m.svcCtx.Redis.SetNX(m.svcCtx.Ctx, key, 1, time.Duration(tMsg.Expire)*time.Second) // 5分钟内不再推送
	})
}
